package com.ebt.m.proposal_v2.widget.view;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.ebt.m.R;
import com.ebt.m.proposal_v2.bean.ApplicantEntity;
import com.ebt.m.proposal_v2.bean.InsuranceEntity;
import com.ebt.m.proposal_v2.bean.InsuredEntity;
import com.ebt.m.proposal_v2.helper.PickerHelper;
import com.ebt.m.proposal_v2.interfaces.OnRxClickListener;
import com.ebt.m.proposal_v2.ui.view.InsuranceView;
import com.ebt.m.proposal_v2.utils.DataUtils;
import com.ebt.m.proposal_v2.utils.RxUtils;
import com.ebt.m.proposal_v2.widget.base.CompatLinearLayout;

import java.util.ArrayList;
import java.util.Date;

import butterknife.BindView;

/**
 * 一款主险或附加险
 * <p>主险标识，直接在data中进行设定或判定</p>
 *
 * @author archer.qi
 * Created on 2017/5/11.
 */
public class InsuranceCellView extends CompatLinearLayout {

    /* 计划书Header*/
    @BindView(R.id.insurance_cell_name)
    CompoundTextView insuranceName;
    @BindView(R.id.insurance_cell_edit)
    ImageView actionEdit;
    @BindView(R.id.insurance_cell_delete)
    ImageView actionDelete;

    /* Table*/
    @BindView(R.id.insurance_cell_table)
    TableLayout table;
    @BindView(R.id.insurance_cell_table_header)
    TableRow tableHeader;
    @BindView(R.id.insurance_cell_table_body)
    TableRow tableBody;

    /* Table-Header*/
    @BindView(R.id.insurance_cell_table_header_amount)
    TextView headerAmount;
    @BindView(R.id.insurance_cell_table_header_premium)
    TextView headerPremium;
    @BindView(R.id.insurance_cell_table_header_guarantee)
    TextView headerGuarantee;
    @BindView(R.id.insurance_cell_table_header_payment)
    TextView headerPayment;

    /* Table-Data*/
    /**
     * 保额view
     */
    @BindView(R.id.insurance_cell_table_body_amount)
    TextView bodyCoverage;
    /**
     * 保费view
     */
    @BindView(R.id.insurance_cell_table_body_premium)
    TextView bodyPremium;
    @BindView(R.id.insurance_cell_table_body_guarantee)
    TextView bodyCoveragePeriod;
    @BindView(R.id.insurance_cell_table_body_payment)
    TextView bodyPaymentPeriod;

    /**
     * 每个主险或附加险绑定一条数据
     */
    public InsuranceEntity data;
    private InsuredEntity insuredEntity;
    /**
     * 父UI。通过父UI获取投、被保人
     */
    InsuranceView insuranceView;

    public InsuranceView getInsuranceView() {
        return insuranceView;
    }

    public InsuranceCellView(Context context, InsuranceView insuranceView) {
        super(context);
        this.insuranceView = insuranceView;
    }

    public InsuranceCellView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected int setContentView() {
        return R.layout.proposal_v2_insurance_cell;
    }

    @Override
    protected void onBindView() {

    }

    /**
     * 是否是主险
     *
     * @return
     */
    public boolean isMain() {
        if (data == null) {
            throw new NullPointerException("data is null, please set valid data");
        }
        return data.isMain();
    }

    /**
     * 更新Logo
     */
    private void updateLogo() {
        if (isMain()) {
            insuranceName.setLeftDrawable(getDrawable(R.drawable.ic_label_main));
        } else {
            insuranceName.setLeftDrawable(getDrawable(R.drawable.ic_label_additional));
        }
    }

    /**
     * 设置名称
     *
     * @param name
     */
    private void setName(String name) {
        insuranceName.setText(checkNull(name));
    }

    /**
     * 是否显示删除按钮
     *
     * @param shown
     */
    private void showDeleteBtn(boolean shown) {
        actionDelete.setVisibility(shown ? VISIBLE : GONE);
    }

    /**
     * 设置保险选项
     */
    private void setOptions() {
        if (this.data == null) {
            return;
        }

        //下载后更新
        ArrayList check = checkIfMatchCondition();
        Boolean ret = (Boolean) check.get(0);
        if (ret) {
            this.data.setValidAccordingToInsuredEntityAndInsuranceEntity(true);
            if (this.data.coverage != null) {
                bodyCoverage.setText(
                        TextUtils.isEmpty(this.data.coverage.displayName) ?
                                DataUtils.parseIntValue(this.data.coverage.value) : this.data.coverage.displayName);
            }
            if (this.data.premium != null) {
                bodyPremium.setText(DataUtils.parseIntValue(this.data.premium.displayName));
            }
            if (this.data.coveragePeriod != null) {
                bodyCoveragePeriod.setText(checkNull(this.data.coveragePeriod.displayName));
            } else {
                bodyCoveragePeriod.setText("");
            }
            if (this.data.paymentPeriod != null) {
                bodyPaymentPeriod.setText(checkNull(this.data.paymentPeriod.displayName));
            } else {
                bodyPaymentPeriod.setText("");
            }
        } else {
            //data 设置标志位
            this.data.setValidAccordingToInsuredEntityAndInsuranceEntity(false);

            bodyCoverage.setText("-");
            bodyPremium.setText("-");
            bodyCoveragePeriod.setText("-");
            bodyPaymentPeriod.setText("-");
        }

    }

    public ArrayList<Object> checkIfMatchCondition() {
        String productNameRule = data.getDisplayName() + "规则:";
        String ruleCustomer = "被保人";
        ArrayList<Object> list = new ArrayList<>();
        InsuredEntity insuredEntityTem = null;
        boolean isExemptApplicant = false;
        if (!isMain() && isExemption() && getExemptionType() == 1) {
            isExemptApplicant = true;
            ApplicantEntity ae = getInsuranceView().getApplicantPerson();
            insuredEntityTem = new InsuredEntity();
            insuredEntityTem.sex = ae.sex;
            insuredEntityTem.age = ae.age;
            insuredEntityTem.birthday = ae.birthday;
        } else {
            insuredEntityTem = this.insuredEntity;
        }
        if (isExemptApplicant) {
            ruleCustomer = "投保人";
        }
        if (insuredEntityTem == null || limitData == null) {
            list.add(new Boolean(true));
            return list;
        }
        //检查性别
        if (!checkSexMatchCondition(limitData.accSex, insuredEntityTem.sex)) {
            list.add(new Boolean(false));
            String message = "";
            if ("1".equals(limitData.accSex)) {
                message = productNameRule + ruleCustomer + "性别仅限女";
            } else if ("2".equals(limitData.accSex)) {
                message = productNameRule + ruleCustomer + "性别仅限男";
            }
            list.add(message);
            return list;
        }
        if (!checkMinAgeMatchCondition(limitData.accMinAge, insuredEntityTem.age, insuredEntityTem.birthday)) {
            list.add(new Boolean(false));
            float age = Float.valueOf(limitData.accMinAge);
            list.add(productNameRule + ruleCustomer + "年龄不能小于" + (int) age + "岁");
            return list;
        }

        if (!checkMaxAgeMatchCondition(limitData.accMaxAge, insuredEntityTem.age, insuredEntityTem.birthday)) {
            list.add(new Boolean(false));
            float age = Float.valueOf(limitData.accMaxAge);
            list.add(productNameRule + ruleCustomer + "年龄不能大于" + (int) age + "岁");
            return list;
        }

        if (!checkProfessionMatchCondition(limitData.accOccupation, insuredEntityTem.profession)) {
            list.add(new Boolean(false));
            list.add(productNameRule + ruleCustomer + "职业类别范围为 1 — " + limitData.accOccupation);
            return list;
        }
        list.clear();
        list.add(new Boolean(true));
        return list;
    }

    public static final int CHECK_TYPE_AGE = 1;
    public static final int CHECK_TYPE_AGE_MIN = 11;
    public static final int CHECK_TYPE_AGE_MAX = 12;
    public static final int CHECK_TYPE_SEX = 2;
    public static final int CHECK_TYPE_CAREER = 3;

    public ArrayList<Object> checkIfMatchCondition(InsuredEntity insuredEntityTem) {

        String ruleCustomer = "被保人";
        InsuredEntity insuredEntityTem1 = null;
        boolean isExemptApplicant = false;
        if (!isMain() && isExemption() && getExemptionType() == 1) {
            isExemptApplicant = true;
            ApplicantEntity ae = getInsuranceView().getApplicantPerson();
            insuredEntityTem1 = new InsuredEntity();
            insuredEntityTem1.sex = ae.sex;
            insuredEntityTem1.age = ae.age;
            insuredEntityTem1.birthday = ae.birthday;
        } else {
            insuredEntityTem1 = insuredEntityTem;
        }
        if (isExemptApplicant) {
            ruleCustomer = "投保人";
        }

        ArrayList<Object> list = new ArrayList<>();
        if (insuredEntityTem == null || limitData == null) {
            list.add(new Boolean(true));
            return list;
        }
        //检查性别
        if (!checkSexMatchCondition(limitData.accSex, insuredEntityTem1.sex)) {
            list.add(new Boolean(false));
            String message = "";
            if ("1".equals(limitData.accSex)) {
                message = ruleCustomer + "性别仅限女";
            } else if ("2".equals(limitData.accSex)) {
                message = ruleCustomer + "性别仅限男";
            }
            list.add(message);
            list.add(new Integer(CHECK_TYPE_SEX));
            return list;
        }
        if (!checkMinAgeMatchCondition(limitData.accMinAge, insuredEntityTem1.age, insuredEntityTem1.birthday)) {
            list.add(new Boolean(false));
            float age = Float.valueOf(limitData.accMinAge);
//            list.add("被保人年龄不能小于" + (int)age + "岁");
            list.add(ruleCustomer + "年龄小于最小投保年龄，修改后会导致选择的险种无法计算");
            list.add(new Integer(CHECK_TYPE_AGE));
            list.add(new Integer(CHECK_TYPE_AGE_MIN));
            return list;
        }

        if (!checkMaxAgeMatchCondition(limitData.accMaxAge, insuredEntityTem1.age, insuredEntityTem1.birthday)) {
            list.add(new Boolean(false));
            float age = Float.valueOf(limitData.accMaxAge);
//            list.add("被保人年龄不能大于" + (int)age + "岁");
            list.add(ruleCustomer + "年龄大于最大投保年龄，修改后会导致选择的险种无法计算");
            list.add(new Integer(CHECK_TYPE_AGE));
            list.add(new Integer(CHECK_TYPE_AGE_MAX));
            return list;
        }

        if (!checkProfessionMatchCondition(limitData.accOccupation, insuredEntityTem1.profession)) {
            list.add(new Boolean(false));
            list.add(ruleCustomer + "职业类别范围为 1 — " + limitData.accOccupation);
            list.add(new Integer(CHECK_TYPE_CAREER));
            return list;
        }

        list.clear();
        list.add(new Boolean(true));
        return list;
    }


    /**
     * 投保性别sex限制
     * <p>0：没有限制 </p>
     * <p>1：表示限制只能女性投保 </p>
     * <p>2：表示限制只能男性投保</p>
     *
     * @param limitSex
     * @param insuredSex
     * @return
     */
    private boolean checkSexMatchCondition(String limitSex, int insuredSex) {
        if (TextUtils.isEmpty(limitSex)) {
            return true;
        }
        try {
            Integer limitSexInt = Integer.valueOf(limitSex);
            if (limitSexInt == null) {
                return true;
            }
            if (limitSexInt != null) {
                if (limitSexInt == 0) {//没有限制
                    return true;
                } else if ((limitSexInt - 1) == insuredSex) {
                    return true;
                } else {
                    return false;
                }
            }
        } catch (Exception e) {
        }
        return true;
    }

    //检查年龄最小限制
    private boolean checkMinAgeMatchCondition(String minAge, int insuredAge, String birthday) {
        if (TextUtils.isEmpty(minAge)) {
            return true;
        }
        try {
            Float ageFloat = Float.valueOf(minAge);
            if (ageFloat == null) {
                return true;
            }
            if (ageFloat != null) {
                if (ageFloat >= 1) {
                    return insuredAge >= (int) ageFloat.floatValue();
                } else {
                    if (insuredAge >= 1) {
                        return true;
                    } else {
                        Date minBirthday = DataUtils.getBirthdayByAge(ageFloat);
                        if (TextUtils.isEmpty(birthday)) {
                            if (ageFloat > 0.00001f) {//要求的最小年龄大于1天
                                return false;
                            } else {
                                return true;//这种可能几乎没有
                            }
                        }
                        Date insuredBirthday = com.ebt.m.utils.DateUtils.stringToDateTime(birthday);
                        if (insuredBirthday == null || minBirthday == null) {
                            return true;
                        }
                        return insuredBirthday.before(minBirthday);
                    }
                }
            }
        } catch (Exception e) {
        }
        return true;
    }

    //检查年龄最大限制
    private boolean checkMaxAgeMatchCondition(String maxAge, int insuredAge, String birthday) {
        if (TextUtils.isEmpty(maxAge)) {
            return true;
        }
        try {
            Float ageFloat = Float.valueOf(maxAge);
            if (ageFloat == null) {
                return true;
            }
            if (ageFloat != null) {
                if (ageFloat >= 1) {
                    return insuredAge <= (int) ageFloat.floatValue();
                } else {
                    if (insuredAge > 1) {
                        return false;
                    } else {
                        //yyyy-MM-dd
                        Date maxBirthday = DataUtils.getBirthdayByAge(ageFloat);
                        if (TextUtils.isEmpty(birthday)) {
                            return true;
                        }
                        Date insuredBirthday = com.ebt.m.utils.DateUtils.stringToDateTime(birthday);
                        if (insuredBirthday == null || maxBirthday == null) {
                            return true;
                        }
                        return insuredBirthday.getTime() <= maxBirthday.getTime();
                    }
                }
            }
        } catch (Exception e) {
        }
        return true;
    }

    //    职业类别范围 （1-6） 6：表示 1到6类都可 5：表示 1到5类都可，以此类推
    private boolean checkProfessionMatchCondition(String limitProfession, int insuredProfession) {
        if (TextUtils.isEmpty(limitProfession)) {
            return true;
        }
        try {
            Integer limitProfessionInt = Integer.valueOf(limitProfession);
            if (limitProfessionInt == null) {
                return true;
            }
            if (limitProfessionInt != null) {
                return limitProfessionInt >= insuredProfession;
            }
        } catch (Exception e) {
        }
        return true;
    }

    /**
     * 数据变更时更新View
     */
    private void updateViewSetDataChanged() {
        if (this.data == null) {
            return;
        }
        updateLogo();
        setName(this.data.productName);
        showDeleteBtn(!this.data.isBindingMain);
        setOptions();
    }

    /**
     * 设置数据
     *
     * @param data
     */
    public void setData(InsuranceEntity data) {
        this.data = data;
        this.limitData = new LimitData(data.accMaxAge, data.accMinAge, data.accOccupation, data.accSex);
        updateViewSetDataChanged();
    }

    /**
     * 获取数据
     *
     * @return
     */
    public InsuranceEntity getData() {
        return data;
    }

    /**
     * 添加事件
     *
     * @param listener
     */
    public void setActionListener(OnActionListener listener) {
        if (listener != null) {
            RxUtils.click(actionEdit, new OnRxClickListener() {
                @Override
                public void onRxClick(View view) {
                    //显示不可保的对话框
                    ArrayList check = checkIfMatchCondition();
                    Boolean ret = (Boolean) check.get(0);
                    if (ret) {
                        listener.onEdit(InsuranceCellView.this);
                    } else {
                        //弹出对话框
                        //被保人信息与险种规则不匹配，暂不可编辑
                        PickerHelper.tip("被保人信息与险种规则不匹配，暂不可编辑").show(getFragmentManager(), "InsuranceCellView data invalid");
                    }
                }
            });
            RxUtils.click(actionDelete, view -> listener.onDelete(InsuranceCellView.this));
        }
    }

    public interface OnActionListener {
        void onEdit(InsuranceCellView view);

        void onDelete(InsuranceCellView view);
    }

    public void setInsuredEntity(InsuredEntity insuredEntity) {
        this.insuredEntity = insuredEntity;
    }

    private LimitData limitData;

    public static class LimitData {
        public String accMaxAge;
        public String accMinAge;
        public String accOccupation;
        public String accSex;

        public LimitData(String accMaxAge, String accMinAge, String accOccupation, String accSex) {
            this.accMaxAge = accMaxAge;
            this.accMinAge = accMinAge;
            this.accOccupation = accOccupation;
            this.accSex = accSex;
        }
    }

    /**
     * 是否是豁免险
     *
     * @return
     */
    public boolean isExemption() {
        return data.isExemption();
    }

    /**
     * 获取豁免人类型： 0 不豁免  1 豁免投保人 2 豁免被保人
     *
     * @return
     */
    public int getExemptionType() {
        return data.getExemptionType();
    }

}